package com.channel.connector.ctripos.common.constant;

import com.channel.connector.ctripos.common.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class CtripOSCommonUtil {

    private static Log log = LogFactory.getLog(CtripOSCommonUtil.class);

    public static Boolean sendEmailFlag = true;

    private static ThreadPoolTaskExecutor sendEmailExecutor = null;

    private static ThreadPoolTaskExecutor logTaskExecutor = null;

    public static XMLGregorianCalendar dateToXMLGregorianCalendar(Date date) {

        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        XMLGregorianCalendar gc = null;
        try {
            gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        } catch (Exception e) {
            log.error("Date转换为XMLGregorianCalendar失败.", e);
        }
        return gc;
    }

    public static Date xmlGregorianCalendarToDate(XMLGregorianCalendar cal)
            throws Exception {
        return cal.toGregorianCalendar().getTime();
    }


    public static Date converterCtripDate(String dateStr) {
        Date result = null;
        int index = dateStr.indexOf("T");
        if (dateStr.indexOf("00:00:00") > -1) {
            result = DateUtil.stringToDate(dateStr.substring(0, index));
        } else {
            result = DateUtil.stringToDate(dateStr.replace("T", " "),
                    "yyyy-MM-dd HH:mm:ss");
        }
        return result;
    }

    public static String fromCtripDate(Date date) {
        String result = "";
        String dstr = DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss");
        if (dstr.indexOf(" ") > 0) {
            result = dstr.replace(" ", "T");
        }
        return result;
    }

    public static String buildDefaultToken() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }
}
